<template>
  <view class="group-box">
    <view
      class="common-header-bg header-box"
      :style="{ 'background-image': 'url(' + state.bannerImage + ')' }"
    >
      <view class="header-tab" :style="{ paddingTop: useAppData.titleHeight + 3 + 'px' }">
        <view class="header-item" @tap="gotoChat">对话</view>
        <view class="header-item header-item-active">跑团</view>
        <view @tap="gotoMe">我的</view>
      </view>
      <view class="banner-box" @tap="gotoActiveDesc">
        <view class="banner-btn" @click.stop="onChangeGroup">
          <image src="../static/icon-change.png"></image>
          <text>{{ state.bannerTxt }}PK赛</text>
        </view>
      </view>
    </view>
    <view class="con-box">
      <!-- 未入团 -->
      <view class="group-nologin" v-if="!useGroupData?.groupInfo || !state.token">
        <image class="icon-wp" src="../static/icon-wp.png"></image>
        <view class="btn-box">
          <view class="btn" v-if="state.token" @tap="gotoLogin(1)">创建我的跑团</view>
          <!-- 登录 未入团 -->
          <view class="btn" v-if="state.token" @tap="onScanCode">加入跑团</view>
          <!-- 未登陆 -->
          <view v-if="!state.token" class="btn" @tap="gotoLogin(2)">登录查看跑团</view>
        </view>
      </view>
      <!-- 已入团 -->
      <view class="my-group" v-if="state.token && useGroupData?.groupInfo">
        <view class="group-header">
          <view class="header-left">
            <image class="icon-wp" src="../static/icon-wp.png"></image>
            <image
              class="icon-qr"
              src="../static/icon-erweima.png"
              @tap="onOpenQrcode"
            ></image>
          </view>
          <view class="header-add" @tap="openSharePopup">
            <image src="../static/icon-add.png"></image>
            <text>添加成员</text>
          </view>
        </view>
        <view class="group-info" @tap="gotoPerson">
          <view class="group-left">
            <view class="group-avart">
              <image class="icon" :src="useGroupData?.groupInfo?.groupHeadImage"></image>
            </view>
            <view class="info-box">
              <view class="info-title">
                <text class="g-name">{{ useGroupData?.groupInfo?.groupName }}</text>
                <text class="g-role" v-if="useGroupData?.groupInfo?.groupRole == 1"
                  >团长</text
                >
              </view>
              <view class="info-member">
                {{ useGroupData?.groupInfo?.memberNumber }}/{{
                  useGroupData?.groupInfo?.limitNumber
                }}成员
              </view>
              <view> 累计{{ useGroupData?.groupInfo?.totalDistance }}公里 </view>
            </view>
          </view>
          <image class="icon-arrow-right" src="../../static/more@2x.png"></image>
          <image class="bg-run" src="../static/bg-run.png"></image>
        </view>
      </view>
      <Ranking ref="rankRef" :isChangeGroup="state.isChangeGroup"></Ranking>
      <PictureUpload
        ref="pictureUploadRef"
        :getRankingData="onGetGroupRankData"
      ></PictureUpload>
    </view>
    <uni-popup ref="loginDialogRef" type="dialog">
      <uni-popup-dialog
        title="请先登录你的账号"
        cancelText="取消"
        confirmText="立即登录"
        content="登录后可创建/查看跑团"
        @close="handleLoginClose"
        @confirm="handleLoginConfirm"
      ></uni-popup-dialog>
    </uni-popup>
    <uni-popup ref="alertDialogRangeRef" type="dialog">
      <uni-popup-dialog
        :title="state.title"
        :cancelText="state.cancelText"
        :confirmText="state.confirmText"
        :content="state.content"
        @close="handleClose"
        @confirm="handleConfirm"
      ></uni-popup-dialog>
    </uni-popup>
    <!-- 提示窗示例 -->
    <uni-popup ref="alertDialog" type="dialog">
      <uni-popup-dialog
        cancelText="取消"
        confirmText="确定"
        title=""
        @confirm="dialogConfirmTrans"
        @close="dialogClose"
      >
        <view class="dialog-content">
          <view class="label">{{ state.joinGroupMessage }}</view>
        </view>
      </uni-popup-dialog>
    </uni-popup>
    <ShareGroup ref="shareGroupRef"></ShareGroup>
  </view>
</template>

<script setup>
import {
  onLaunch,
  onLoad,
  onShow,
  onHide,
  onUnload,
  onShareAppMessage,
  onShareTimeline,
} from "@dcloudio/uni-app";
import { ref, reactive, watch, onMounted, nextTick } from "vue";
import Ranking from "../components/ranking.vue";
import PictureUpload from "../components/pictureUpload";
import * as API from "../../api/api";
import { getTime, checkUserInfo } from "../../utils/util";
import { storeToRefs } from "pinia";
import { useGroupStore } from "../../store/group";
import { useAppStore } from "../../store/app";
import { useShareStore } from "../../store/share";
import { userLoginStore } from "../../store/userLogin";
import { useRunInfoStore } from "../../store/runInfo";
import ShareGroup from "../components/shareGroup.vue";
const useShareData = useShareStore();
const useAppData = useAppStore();
const useGroupData = useGroupStore();
const userLoginData = userLoginStore();
const useRunInfoData = useRunInfoStore();
const pictureUploadRef = ref(null);
const alertDialogRangeRef = ref(null);
const loginDialogRef = ref(null);
const shareGroupRef = ref(null);
const alertDialog = ref(null);
const rankRef = ref(null);
const { familyBannerImg, superBannerImg } = storeToRefs(useRunInfoData);
const state = reactive({
  title: "请先登录你的账号",
  cancelText: "取消",
  confirmText: "立即登录",
  content: "登录后可创建/查看跑团",
  token: null,
  userInfo: null,
  groupInfo: null,
  groupList: [],
  createGroup: false,
  joinType: null,
  joinGroupId: null,
  enterType: "navigate",
  hidePop: false,
  joinGroupMessage: "",
  bannerTxt: "家庭跑团",
  bannerImg: familyBannerImg.value,
  isChangeGroup: false,
  groupType: 0
});

// onShareAppMessage((res) => {
//   const pages = getCurrentPages();
//   const currentPage = pages[pages.length - 1];
//   const options = currentPage.options;
//   let path = `${currentPage.route}?shareUserId=${state.userInfo?.customers?.customerId}&groupId=${useGroupData?.groupInfo?.groupId}&type=share&groupType=${state.groupType}`
//   console.log("dedede", options, path, currentPage)
//   return {
//     title: "2024廊坊首届全民健康走跑大会火热进行中，奔跑廊坊，体育场等你！",
//     path,
//     imageUrl: useGroupData.groupInfo.groupHeadImage,
//   };
// });
// onShareTimeline((res) => {
//   // return useShareData.shareInfo
// });

const onOpenQrcode = () => {
  shareGroupRef?.value?.openQrcodeRef();
};

const openSharePopup = () => {
  shareGroupRef.value.openPopup();
};
// 入团判断
const groupJudgeJoin = () => {
  let params = {
    userId: state.userInfo?.customers?.customerId,
    groupId: state.joinGroupId,
  };
  console.log("入团判断参数===", params);
  API.groupJudgeJoin(params)
    .then((res) => {
      if (res.code === 0) {
        state.joinType = res.data;
        console.log("入团返回参数", res.data, state.joinType);
        onJudgePop();
      }
    })
    .catch((err) => {});
};

const gotoActiveDesc = () => {
  uni.navigateTo({
    url: "/runGroupPages/activeDesc/index",
  });
};

const onJudgePop = () => {
  console.log("state.joinType", state.joinType);
  state.title = "";
  if (state.joinType && state.joinType !== 1000) {
    // 无团已满员
    if (state.joinType === 1001) {
      state.cancelText = "加入其他跑团";
      state.confirmText = "创建跑团";
      state.content = "该跑团已满员，您可以自己创建跑团或加入其他跑团";
    }
    // 有团且是团员
    if (state.joinType === 1002) {
      state.cancelText = "取消";
      state.confirmText = "确定加入";
      state.content = "您已加入其他跑团，确认加入新跑团将从原跑团移出";
    }
    // 有团且是团长且团人数>1
    if (state.joinType === 1003) {
      state.cancelText = "知道了";
      state.confirmText = "";
      state.content = "您已有自己的跑团了，暂时不能加入该跑团";
    }
    // 有团且是团长且团人数=1
    if (state.joinType === 1004) {
      state.cancelText = "取消";
      state.confirmText = "确定加入";
      state.content = "确认加入该跑团？加入后您自己的跑团将会解散";
    }
    if (state.joinType === 1005) {
      state.joinGroupMessage = "用户信息不完整，请完善个人资料";
      alertDialog.value.open();
      return;
    }
    alertDialogRangeRef.value.open();
  } else {
    onJoinGroup();
  }
};

const onJoinGroup = () => {
  let params = {
    userId: state.userInfo?.customers?.customerId,
    groupId: state.joinGroupId,
    joinTypeCode: state.joinType,
  };
  API.joinGroup(params)
    .then((res) => {
      if (res.code === 0) {
        uni.showToast({
          title: "您已成功加入该跑团",
          icon: "none",
        });
        useGroupData.onGetGroupInfo().then((res) => {
          setTimeout(() => {
            onGetGroupRankData();
          }, 1500);
        });
      } else if (res.code === 205) {
        state.joinGroupMessage = res.message;
      } else {
        uni.showToast({
          title: res.message,
          icon: "none",
        });
      }
    })
    .catch((err) => {});
};

const gotoLogin = (type) => {
  if (!state.token) {
    onShowLoginPop();
  } else {
    if (!checkUserInfo(state.userInfo?.customers)) {
      state.joinGroupMessage = "用户信息不完整，请完善个人资料";
      alertDialog.value.open();
    } else {
      pictureUploadRef?.value?.openPopup();
    }
  }
};

const gotoPerson = () => {
  uni.navigateTo({
    url: `/runGroupPages/myGroup/index`,
  });
};

const handleLoginConfirm = () => {
  userLoginData.setRedirectUrl(
    `/runGroupPages/group/groupInfo?enterType=${state.enterType}&joinGroupId=${state.joinGroupId}`
  );
  uni.navigateTo({
    url: "/pages/login/login",
  });
};

const handleLoginClose = () => {
  loginDialogRef?.value?.close();
};

const dialogConfirmTrans = () => {
  uni.navigateTo({
    url: "/pages/personInfo/personInfo",
  });
};

const handleConfirm = () => {
  alertDialogRangeRef?.value?.close();
  state.hidePop = true;
  uni.setStorageSync("hidePop", state.hidePop);
  // 无团已满员
  if (state.joinType === 1001) {
    // 确定-创建跑团
    gotoLogin(1);
  }
  // 有团且是团员
  if (state.joinType === 1002) {
    // 确定-退出原团加入其他团
    onJoinGroup();
  }
  // 有团且是团长且团人数>1
  if (state.joinType === 1003) {
  }
  // 有团且是团长且团人数=1
  if (state.joinType === 1004) {
    // 确定-解散原团加入其他团
    onJoinGroup();
  }
  if (state.joinType === 1005 || !state.userInfo?.customers?.customerName) {
    uni.navigateTo({
      url: "/pages/personInfo/personInfo",
    });
  }
};

const handleClose = () => {
  alertDialogRangeRef?.value?.close();
  state.hidePop = true;
  uni.setStorageSync("hidePop", state.hidePop);
  // 无团已满员
  if (state.joinType === 1001) {
    // 确定-加入其他跑团-扫二维码进团
    onScanCode();
  }
  // 有团且是团员
  if (state.joinType === 1002) {
  }
  // 有团且是团长且团人数>1
  if (state.joinType === 1003) {
  }
  // 有团且是团长且团人数=1
  if (state.joinType === 1004) {
  }
};

const onShowLoginPop = () => {
  loginDialogRef?.value?.open();
};

const onScanCode = () => {
  if (!checkUserInfo(state.userInfo?.customers)) {
    state.joinGroupMessage = "用户信息不完整，请完善个人资料";
    alertDialog.value.open();
  } else {
    uni.scanCode({
      success(res) {
        console.log(res, "扫码结果");
        state.hidePop = false;
        uni.setStorageSync("hidePop", state.hidePop);
        let fullPath = decodeURIComponent(res.path);
        let url = fullPath.includes("?") ? fullPath.split("?")[0] : fullPath;
        let queryAll = fullPath.includes("?") ? fullPath.split("?")[1] : [];
        let queryTypeId = queryAll.split("scene=")[1];
        let query1 = queryTypeId.split("&")[0];
        let query2 = query1.split("=");
        state.joinGroupId = query2 ? query2[1] : null;
        uni.redirectTo({
          url: `/${url}?enterType=share&joinGroupId=${state.joinGroupId}`,
        });
      },
      fail(err) {
        console.log("扫描失败", err);
        uni.showToast({
          title: "扫描失败",
          icon: "none",
        });
      },
    });
  }
};

const gotoMe = () => {
  uni.reLaunch({
    url: "/pages/me/me",
  });
};

const gotoBack = () => {
  uni.navigateBack();
};

const gotoChat = (url) => {
  uni.reLaunch({
    url: "/pages/chat/chat",
  });
};

const onGetGroupRankData = () => {
  nextTick(() => {
    rankRef?.value?.onGetGroupRank();
  });
};

const parseUrlParams = (url) => {
  var paramString = url.split("?")[1];
  var paramPairs = paramString.split("&");
  var params = {};

  paramPairs.reduce(function (params, pair) {
    var parts = pair.split("=");
    var key = parts[0];
    var value = decodeURIComponent(parts[1] || "");

    if (params[key]) {
      params[key].push(value);
    } else {
      params[key] = [value];
    }

    return params;
  }, params);

  return params;
};

const handleLogin = () => {
  uni.login({
    provider: "weixin",
    success: (res) => {
      userLoginData
        .getOpenId(res.code)
        .then((res1) => {
          userLoginData.getUserInfoData().then((res2) => {
            state.userInfo = uni.getStorageSync("userInfo")
              ? JSON.parse(uni.getStorageSync("userInfo"))
              : null;
            state.token = uni.getStorageSync("token")
              ? uni.getStorageSync("token")
              : null;
            // 判断入团状态
            useGroupData.onGetGroupInfo().then((res) => {
              if (
                !useGroupData.groupInfo ||
                !useGroupData.groupInfo.groupId ||
                useGroupData.groupInfo.groupId !== state.joinGroupId
              ) {
                state.hidePop = false;
              } else {
                state.hidePop = true;
              }
              console.log("扫码进入==333", state.hidePop);
              if (!state.hidePop) {
                console.log("扫码进入==444");
                groupJudgeJoin();
              }
            });
          });
        })
        .catch((err) => {
          // 去登陆
          onShowLoginPop();
        });
    },
    fail: (err) => {},
  });
};

const onChangeGroup = () => {
  state.groupType = state.groupType == 0 ? (state.groupType = 1) : (state.groupType = 0);
  state.isChangeGroup = !state.isChangeGroup
  useGroupData.onGetGroupInfo().then((res) => {
    onGetGroupRankData();
  });
};

onLoad((options) => {
  state.groupType = options?.groupType || 0;
  state.userInfo = uni.getStorageSync("userInfo")
    ? JSON.parse(uni.getStorageSync("userInfo"))
    : null;
  state.token = uni.getStorageSync("token") ? uni.getStorageSync("token") : null;
  let pages = getCurrentPages();
  let currentPage = pages[pages.length - 1];
  let optionsSync = uni.getLaunchOptionsSync();
  console.log("场景值===", optionsSync, currentPage);

  if (
    currentPage.options.enterType === "share" &&
    currentPage.options.joinGroupId &&
    currentPage.options.joinGroupId !== "null"
  ) {
    state.enterType = "share";
    state.joinGroupId = currentPage.options.joinGroupId;
    // 分享或者扫描进入时
    if (!state.token) {
      // 去登陆
      // onShowLoginPop()
      handleLogin();
    } else {
      useGroupData.onGetGroupInfo().then((res) => {
        if (
          !useGroupData.groupInfo ||
          !useGroupData.groupInfo.groupId ||
          useGroupData.groupInfo.groupId != state.joinGroupId
        ) {
          state.hidePop = false;
        } else {
          state.hidePop = true;
        }
        if (!state.hidePop) {
          groupJudgeJoin();
        }
      });
    }
  } else if (currentPage.options.type === "share" && currentPage.options.groupId) {
    state.enterType = "share";
    state.joinGroupId = currentPage.options.groupId;
    // 分享或者扫描进入时
    if (!state.token) {
      // 去登陆
      // onShowLoginPop()
      handleLogin();
    } else {
      useGroupData.onGetGroupInfo().then((res) => {
        if (
          !useGroupData.groupInfo ||
          !useGroupData.groupInfo.groupId ||
          useGroupData.groupInfo.groupId != state.joinGroupId
        ) {
          state.hidePop = false;
        } else {
          state.hidePop = true;
        }
        if (!state.hidePop) {
          groupJudgeJoin();
        }
      });
    }
  } else if (
    optionsSync.scene == 1047 ||
    optionsSync.scene == 1048 ||
    optionsSync.scene == 1049 ||
    currentPage.options.scene ||
    currentPage.options.enterType === "share"
  ) {
    state.enterType = "share";
    let queryScene = currentPage.options.scene
      ? decodeURIComponent(currentPage.options.scene).split("&")
      : null;
    let query = queryScene[0].split("=");
    state.joinGroupId = query ? query[1] : null;

    // 分享或者扫描进入时
    if (!state.token) {
      // 去登陆
      // onShowLoginPop()
      handleLogin();
    } else {
      useGroupData.onGetGroupInfo().then((res) => {
        if (
          !useGroupData.groupInfo ||
          !useGroupData.groupInfo.groupId ||
          useGroupData.groupInfo.groupId != state.joinGroupId
        ) {
          state.hidePop = false;
        } else {
          state.hidePop = true;
        }
        if (!state.hidePop) {
          groupJudgeJoin();
        }
      });
    }
  } else {
    state.enterType = "navigate";
    state.joinGroupId = null;
  }
});

onShow(() => {
  state.userInfo = uni.getStorageSync("userInfo")
    ? JSON.parse(uni.getStorageSync("userInfo"))
    : null;
  state.token = uni.getStorageSync("token") ? uni.getStorageSync("token") : null;
  if (state.token) {
    useGroupData.onGetGroupInfo().then((res) => {
      console.log("团信息", res, useGroupData.groupInfo);
      onGetGroupRankData();
    });
  } else {
    onGetGroupRankData();
  }
});

watch(
  () => Number(state.groupType),
  async (newVal, oldVal) => {
    useGroupData.setGroupType(newVal);
    await useRunInfoData.getConfigList()
    if (state.groupType == 1) {
      state.bannerImage = familyBannerImg.value;
      state.bannerTxt = "超级跑团";
    } else {
      state.bannerImage = superBannerImg.value;
      state.bannerTxt = "家庭跑团";
    }
  },
  { immediate: true }
);
</script>

<style lang="scss" scoped>
.header-box {
  width: 100vw;
  height: auto;
  text-align: center;
  // background: url('https://model-capability.oss-cn-beijing.aliyuncs.com/pro/healthRun/paotuan-banner.png') 0 0 no-repeat;
  background-position: 0 0;
  background-repeat: no-repeat;
  background-size: cover;
  position: relative;
  .banner-box {
    height: 430rpx;
    .banner-btn {
      width: 252rpx;
      height: 64rpx;
      background: rgba(255, 255, 255, 0.6);
      border-radius: 32rpx;
      font-size: 28rpx;
      color: rgba(34, 34, 34, 0.8);
      display: flex;
      justify-content: center;
      align-items: center;
      position: absolute;
      left: 50%;
      top: 200rpx;
      transform: translateX(-50%);
      image {
        width: 28rpx;
        height: 28rpx;
        margin-right: 8rpx;
      }
    }
  }
  .rule-box {
    font-family: PingFangSC, PingFang SC;
    font-size: 28rpx;
    color: rgba(34, 34, 34, 0.7);
    position: absolute;
    left: 56rpx;
    bottom: 106rpx;
    display: flex;
    align-items: center;
    .icon-dianji {
      width: 44rpx;
      height: 12rpx;
      margin-left: 12rpx;
    }
  }
}
.con-box {
  height: calc(100vh - 550rpx);
  padding: 0 32rpx;
  box-sizing: border-box;
  margin-top: -84rpx;
  position: relative;
  z-index: 1;
  overflow: auto;
  .icon-wp {
    width: 144rpx;
    height: 40rpx;
    margin-left: 24rpx;
  }
  .group-header {
    height: 84rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .header-left {
      display: flex;
      align-items: center;
      .icon-qr {
        width: 36rpx;
        height: 36rpx;
        margin-left: 12rpx;
      }
    }
    .header-add {
      display: flex;
      align-items: center;
      margin-right: 24rpx;
      image {
        width: 40rpx;
        height: 40rpx;
        margin-right: 8rpx;
      }
      text {
        font-weight: 500;
        font-size: 32rpx;
        color: #263901;
      }
    }
  }
  .group-nologin {
    padding: 26rpx 24rpx 30rpx;
    background: linear-gradient(156deg, #e7ffed 0%, #f6ffe9 100%);
    border-radius: 24rpx;
    box-sizing: border-box;
    font-size: 36rpx;
    .title {
      font-family: FZZYJW--GB1, FZZYJW--GB1;
      color: #033402;
    }
    .btn-box {
      display: flex;
      justify-content: space-around;
      margin-top: 32rpx;
      font-family: PingFangTC, PingFangTC;
      color: #fff;
      .btn {
        width: 308rpx;
        height: 84rpx;
        background: #08cb8f;
        border-radius: 16rpx;
        text-align: center;
        line-height: 84rpx;
      }
    }
  }
  .my-group {
    height: 276rpx;
    background: linear-gradient(331deg, #f9f72c 0%, #90ff8d 100%);
    border-radius: 24rpx;
    box-sizing: border-box;
    .group-info {
      height: 196rpx;
      background: linear-gradient(156deg, #e7ffed 0%, #f6ffe9 100%);
      border-radius: 24rpx;
      position: relative;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .icon-arrow-right {
        width: 32rpx;
        height: 32rpx;
        flex-shrink: 0;
        margin-right: 24rpx;
      }
      .group-left {
        display: flex;
        align-items: center;
        .group-avart {
          width: 147rpx;
          height: 148rpx;
          margin: 0 16rpx 0 24rpx;
          border-radius: 16rpx;
          overflow: hidden;
          .icon {
            width: 100%;
            height: 100%;
          }
        }
        .info-box {
          font-size: 28rpx;
          color: rgba(34, 34, 34, 0.7);
          position: relative;
          z-index: 1;
          .info-title {
            display: flex;
            align-items: center;
            .g-name {
              max-width: 300rpx;
              font-family: PingFangSC, PingFang SC;
              font-weight: 500;
              font-size: 32rpx;
              color: #222222;
              margin-right: 8rpx;
              overflow: hidden; /* 确保超出容器的文本被裁剪 */
              white-space: nowrap; /* 确保文本在一行内显示 */
              text-overflow: ellipsis; /* 使用省略号表示文本超出 */
            }
            .g-role {
              padding: 2rpx 6rpx;
              background: #c3f2c5;
              border-radius: 8rpx;
              font-size: 20rpx;
              color: #3a8439;
            }
          }
          .info-member {
            margin: 10rpx 0;
          }
        }
      }
      .bg-run {
        width: 330rpx;
        height: 76rpx;
        position: absolute;
        right: 0;
        bottom: 0;
      }
    }
  }
}
.dialog-content {
  .label {
    height: 44rpx;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 32rpx;
    color: #1c1c1e;
    line-height: 44rpx;
    text-align: center;
    font-style: normal;
  }
  .text {
    height: 32rpx;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 24rpx;
    color: #abafba;
    line-height: 32rpx;
    text-align: center;
    font-style: normal;
    margin-top: 16rpx;
  }
}
</style>
